﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace BookDownloader.Core.Implementation.BaseLibEngine.Parser
{
	public class SqlParser<T> where T: class
	{
		protected virtual string LinePattern { get { return @"\((?<Params>.*?)\)[,;]"; } }
		protected virtual string ParamsPattern { get { return String.Empty; }}
		private readonly ISqlStreamProvider sqlStreamProvider;

		public List<T> LoadList(LibFileTypes fileType, List<T> list )
		{
			using (StreamReader rd = sqlStreamProvider.GetReader(fileType))
			{
				string line = null;
				RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline;
				while ((line = rd.ReadLine()) != null)
				{
					if (line.StartsWith("INSERT INTO"))
					{
						Regex regex = new Regex(LinePattern, options);
						MatchCollection values = regex.Matches(line);
						foreach (Match match in values)
						{
							T obj = CreateEntity(match.Groups["Params"].Value);
							if(obj != null)
								list.Add(obj);
						}
					}
				}
				return list;
			}
		}

		private T CreateEntity(string parameters)
		{
			RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline;
			Regex regex = new Regex(ParamsPattern, options);
			MatchCollection values = regex.Matches(parameters);
			T obj = null;
			try
			{
				obj = Utility.CreateObjectFromMatch(values[0], typeof(T)) as T;
			}
			catch{}
	
			return obj;
			
		}

		public SqlParser(ISqlStreamProvider sqlStreamProvider)
		{
			this.sqlStreamProvider = sqlStreamProvider;
		}
	}
}
